package com.rcadmin.busi.stat.service;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.rcadmin.busi.stat.ddl.StatDailyAccess;
import com.rcadmin.busi.stat.dto.AppAccessDto;
import com.rcadmin.busi.stat.dto.AppMonthlyAccessDto;
import com.rcadmin.busi.web.ddl.WebTemplatePackage;
import com.rcadmin.busi.web.service.TemplatePackageService;
import com.rcadmin.core.jpa.BaseDao;
import com.rcadmin.util.DataFormat;

/**
 * 日访问统计服务类
 * 
 * @author tanson lam
 * @create 2016年11月10日
 */
@Component
public class StatDailyAccessService {
	@Resource
	private BaseDao baseDao;
	@Resource
	private TemplatePackageService templatePackageService;

	/**
	 * 查询指定日期范围内的用户网站的访问统计记录
	 * 
	 * @param userId
	 * @return
	 */
	public List<StatDailyAccess> findAccessByLastWeek(Integer userId) {
		Calendar cal = Calendar.getInstance();
		String endDay = DataFormat.DateToString(cal.getTime(),
				DataFormat.DATE_FORMAT2);
		cal.add(Calendar.DATE, -7);
		String startDay = DataFormat.DateToString(cal.getTime(),
				DataFormat.DATE_FORMAT2);
		StringBuilder query = new StringBuilder();
		query.append(" and user_id = ").append(userId);
		query.append(" and day").append(">=").append("'" + startDay + "'");
		query.append(" and day").append("<=").append("'" + endDay + "'");
		return baseDao.find(query.toString(), StatDailyAccess.class);
	}

	 

	/**
	 * 获取上周的日期字符
	 * 
	 * @return
	 */
	public List<String> getLastWeekList() {
		LinkedList<String> weekList = new LinkedList<String>();
		Calendar cal = Calendar.getInstance();
		int n = 7;
		while (n > 0) {
			cal.add(Calendar.DATE, -1);
			weekList.addFirst(DataFormat.DateToString(cal.getTime(),
					DataFormat.DATE_FORMAT2));
			n--;
		}
		return weekList;
	}

	/**
	 * 查找上周访问量，并且按照应用进行分组
	 * 
	 * @param userId
	 * @return
	 */
	public List<AppAccessDto> findLastWeekAndGroupApp(Integer userId) {
		Map<Integer, List<StatDailyAccess>> accessMap = Maps.newHashMap();
		List<StatDailyAccess> accessList = findAccessByLastWeek(userId);
		for (StatDailyAccess statDailyAccess : accessList) {
			List<StatDailyAccess> list = accessMap.get(statDailyAccess
					.getTemplatePackageId());
			if (list == null) {
				list = Lists.newArrayList();
				accessMap.put(statDailyAccess.getTemplatePackageId(), list);
			}
			list.add(statDailyAccess);
		}
		List<WebTemplatePackage> templatelist = templatePackageService
				.findEffTemplatePackageByUserId(userId);
		Map<String, List<StatDailyAccess>> resultMap = Maps.newHashMap();
		for (Integer templatePackageId : accessMap.keySet()) {
			for (WebTemplatePackage webTemplatePackage : templatelist) {
				if (webTemplatePackage.getId().equals(templatePackageId)) {
					List<StatDailyAccess> list = accessMap
							.get(templatePackageId);
					Collections.sort(list, new StatDailyAccessComparator());
					resultMap.put(webTemplatePackage.getPrjUrl(), list);
				}
			}
		}
		List<AppAccessDto> accessResultList = Lists.newArrayList();
		for (String appName : resultMap.keySet()) {
			accessResultList.add(new AppAccessDto(appName, resultMap
					.get(appName)));
		}
		return accessResultList;
	}

	static public class StatDailyAccessComparator implements
			Comparator<StatDailyAccess> {

		@Override
		public int compare(StatDailyAccess o1, StatDailyAccess o2) {
			if (o1.equals(o2) || o1.getId().equals(o2.getId()))
				return 0;

			if (Integer.valueOf(o1.getDay()) > Integer.valueOf(o2.getDay()))
				return 1;
			return -1;
		}
	}

	/**
	 * 查询本月的访问量
	 * 
	 * @param userId
	 * @return
	 */
	public AppMonthlyAccessDto findByCurrentMonth(Integer userId) {
		Calendar cal = Calendar.getInstance();
		String curMonth = String.valueOf(cal.get(Calendar.YEAR))
				+ String.valueOf(cal.get(Calendar.MONTH) + 1);
		cal.add(Calendar.MONTH, -1);
		cal.add(Calendar.DATE, 1);
		String startDay = DataFormat.DateToString(cal.getTime(),
				DataFormat.DATE_FORMAT2);
		cal.add(Calendar.MONTH, +2);
		cal.add(Calendar.DATE, -1);
		String endDay = DataFormat.DateToString(cal.getTime(),
				DataFormat.DATE_FORMAT2);
		StringBuilder query = new StringBuilder();
		query.append(" and user_id = ").append(userId);
		query.append(" and day").append(">=").append("'" + startDay + "'");
		query.append(" and day").append("<=").append("'" + endDay + "'");
		List<StatDailyAccess> accessList = baseDao.find(query.toString(),
				StatDailyAccess.class);
		long pv = 0l;
		long uv = 0l;
		long vv = 0l;
		long ip = 0l;
		for (StatDailyAccess statDailyAccess : accessList) {
			pv += statDailyAccess.getPv();
			uv += statDailyAccess.getUv();
			vv += statDailyAccess.getVv();
			ip += statDailyAccess.getIp();
		}
		return new AppMonthlyAccessDto(curMonth, pv, uv, vv, ip);
	}

}
